/****************************
 * URL解析
 ****************************/

(function () {

	//URL解析结果
	var routeInfo = {};

	/**
	 * 查看该接口是否存在
	 **/
	exports.APIisExist = function (req, res, next) {

		//获取一级菜单名
		var firstMenuLevelName = req.params.firstMenuLevel;

		//获取二级菜单名称
		var secondMenuLevelName = req.params.secondMenuLevel;

		//拼接完整接口地址
		var resultApiName = '/' + firstMenuLevelName + '/' + secondMenuLevelName;

		//查看该接口是否注册(存在)
		if (APIConfig.API[resultApiName] == undefined) {

			//如果该接口不存在
			API_forwarded(req, res, resultApiName);
			return;
			
		}

		//记录一级菜单名
		routeInfo.firstMenuLevelName = firstMenuLevelName;

		//记录二级菜单名
		routeInfo.secondMenuLevelName = secondMenuLevelName;

		//记录接口完整名称
		routeInfo.apiFullName = resultApiName;

		//保存原始URL地址
		routeInfo.reqUrl = req.url;


		next();

	};


	/**
	 * 查看该接口请求方式是否正确
	 **/
	exports.APIisMethod = function (req, res, next) {

		//获取请求方式
		var method = req.method;

		//获取该接口支持的请求方式
		var apiMethod = APIConfig.API[routeInfo.apiFullName].method;

		//判断该接口
		if (apiMethod != 'ALL') {
			if (apiMethod != method) {
				return RES.response(res, false, MESSAGE.apiError.noMethod);
			}
		}

		//接口请求方式
		routeInfo.method = method;

		//接口注册请求方式
		routeInfo.apiMethod = apiMethod;

		next();

	};

	/**
	 * 解析接口参数信息
	 **/
	exports.APIgetParams = function (req, res, next) {

		//判断请求方式，获取相应参数
		if (routeInfo.method == 'GET' || routeInfo.method == 'POST') {

			//获取RESTFUL参数
			var restfulParams = req.params[0];

			//解析RESTFUL参数,判断是否存在restful参数
			if (restfulParams != undefined) {

				//获取解析后的restful参数
				resultRestFul = common.parseRestFulParams(restfulParams);
				if (!resultRestFul) {
					return RES.response(res, false, MESSAGE.apiError.noRestful);
				}

				//保存最终restful参数

				routeInfo.restfulParams = resultRestFul;

			}else{
                routeInfo.restfulParams = {};
            }

			if (routeInfo.method == 'POST') {

				//保存最终body参数
				routeInfo.bodyParams = req.body;
			}

		} else {
			return RES.response(res, false, MESSAGE.apiError.noMethod);
		}

		//向外传递最终结果
		req.routeInfo = routeInfo;

		next();

	};

	/**
	 * 参数信息验证
	 **/
	exports.APIParamsVerification = function (req, res, next) {

		//对必传GET参数进行验证
		var getVerification = APIConfig.API[routeInfo.apiFullName].getMustParams;
		if (getVerification != undefined) {

			//获取需要验证的KEY数组
			var getVerificationKeyArray = common.getJsonKeyArray(getVerification);

			//获取restful参数KEY数组
			var restfulKeyArr = common.getJsonKeyArray(routeInfo.restfulParams);

			//求缺少的参数信息(获取两个数组的差集)
			var noRestFulParamsArr = common.minus(getVerificationKeyArray, restfulKeyArr);

			//缺少参数
			if (noRestFulParamsArr.length > 0) {
				RES.response(res, false, '缺少RESTFUL参数 :' + noRestFulParamsArr.join(","));
				return;
			}

			//对GET参数格式进行验证
			for (var k in routeInfo.restfulParams) {

				var key = k;
				var value = routeInfo.restfulParams[k];
				var rule = getVerification[k];

				//获取验证结果
				var errorMessage = V.paramsV(key, value, rule);

				//返回提示信息
				if (errorMessage) {
					return RES.response(res, false, errorMessage);
				}
			}
		}

		//对非必传GET参数进行验证
		var getNoMustVerification = APIConfig.API[routeInfo.apiFullName].getNoMustParams;
		if (getNoMustVerification != undefined) {

			//对GET参数格式进行验证
			for (var k in routeInfo.restfulParams) {

				var key = k;
				var value = routeInfo.restfulParams[k];
				var rule = getNoMustVerification[k];

				//获取验证结果
				var errorMessage = V.paramsV(key, value, rule);

				//返回提示信息
				if (errorMessage) {
					return RES.response(res, false, errorMessage);
				}
			}
		}


		//对POST参数进行验证
		var postVerification = APIConfig.API[routeInfo.apiFullName].postMustParams;



		if (postVerification != undefined) {

			//获取需要验证的KEY数组
			var postVerificationKeyArray = common.getJsonKeyArray(postVerification);

			//获取restful参数KEY数组
			var postKeyArr = common.getJsonKeyArray(routeInfo.bodyParams);

			//求缺少的参数信息(获取两个数组的差集)
			var noPostParamsArr = common.minus(postVerificationKeyArray, postKeyArr);

			//缺少参数
			if (noPostParamsArr.length > 0) {
				RES.response(res, false, '缺少BODY参数 :' + noPostParamsArr.join(","));
				return;
			}

			//对POST参数格式进行验证
			for (var k in routeInfo.bodyParams) {

				var key = k;
				var value = routeInfo.bodyParams[k];
				var rule = postVerification[k];

				//获取验证结果
				var errorMessage = V.paramsV(key, value, rule);

				//返回提示信息
				if (errorMessage) {
					return RES.response(res, false, errorMessage);
				}
			}

		}

		//对非必传POST参数进行验证
		var postNoMustVerification = APIConfig.API[routeInfo.apiFullName].postNoMustParams;
		if (postNoMustVerification != undefined) {

			//对GET参数格式进行验证
			for (var k in routeInfo.bodyParams) {

				var key = k;
				var value = routeInfo.bodyParams[k];
				var rule = postNoMustVerification[k];

				//获取验证结果
				var errorMessage = V.paramsV(key, value, rule);

				//返回提示信息
				if (errorMessage) {
					return RES.response(res, false, errorMessage);
				}
			}
		}

		next();

	};

	/* 
	 * token验证
	 */
	 exports.tokenValidate = function (req, res, next) {
		
		//获取请求方式
		var method = req.method;

		if(method == 'GET'){
			return next();
		}

		/*** 查看是否是白名单中的接口 ***/
		
		//获取一级菜单名
		var firstMenuLevelName = req.params.firstMenuLevel;
		
		//获取二级菜单名称
		var secondMenuLevelName = req.params.secondMenuLevel;
		
		//拼接完整接口地址
		var resultApiName = '/' + firstMenuLevelName + '/' + secondMenuLevelName;

		if( common.containsArr(config.tokenWhiteList,resultApiName) ){
			return next();
		}

		/*
		//获取header头中的token
		var usertoken = req.headers.usertoken;
		if(usertoken == undefined){
			return RES.response(res, false, "检测到您是非法请求");
		}

		//获取服务器的token
		db.where({ut_token:usertoken}).select("art_user_token",function(result){
			
			if(result == 'ERROR'){
				return RES.response(res, false, "服务器错误，请重新尝试");
			}
			
			if(result.length <= 0){
				return RES.response(res, false, "检测到您是非法请求");
			}

			var tokenInfo = result[0];

			//查看是否过期
			var nowtime = common.nowTime(false);

			if(nowtime > tokenInfo.aut_end_time){
				return RES.response(res, false, "token_expired");
			}else{
				
				//token验证通过，允许继续操作，重新更新token过期时间
				var newtime = common.nowTime(false) + (3600 * 24 * 7)
				
				var updateParams = {
					aut_end_time : newtime
				};

				//重新更新token的过期时间
				db.where({aut_token:usertoken}).update(updateParams,"art_user_token",function(result){
					next();
				});
			}

		});
		*/
		next();
	 }


	 /**
	 * 接口转发处理
	 **/
	var API_forwarded = function (req, res, apiName) {


		if(config.base.isOnAuth){

			//验权操作
			auth.authAction(req,res,function(){

				/** 请求核心层同名端口处理 **/
				//如果有RESTFUL参数则获取
				var tempRestfulParams = "";
				if (req.params[0] != undefined) {
					tempRestfulParams = req.params[0];
				}

				//获取请求方式
				var tempMethod = req.method !='GET'?'POST':'GET';
						
				//如果有BODY参数则获取
				var tempBodyParams = {};
				if (tempMethod == 'POST' && !(common.isNullObj(req.body))) {
					tempBodyParams = req.body;
				}

				//拼接核心层最终地址
				var core_server = encodeURI( config.core_server.url + apiName + "/" + tempRestfulParams );

				//向核心层发起请求
				R.SEND_HTTP(
						req,
						{
							url    : core_server,	   //请求地址
							method : tempMethod,	   //请求方式
							data   : tempBodyParams	 //body参数
						},
						function (err, data) {

							// 判断是否有错误信息
							if (err) {
								return RES.response(res, false, data);
							}
							return RES.response(res, true, data);
						});

			});


		}else{

			console.log("请求转发...");


			/** 请求核心层同名端口处理 **/
			//如果有RESTFUL参数则获取
			var tempRestfulParams = "";
			if (req.params[0] != undefined) {
				tempRestfulParams = req.params[0];
			}

			//获取请求方式
			var tempMethod = req.method !='GET'?'POST':'GET';

			//如果有BODY参数则获取
			var tempBodyParams = {};
			if (tempMethod == 'POST' && !(common.isNullObj(req.body))) {
				tempBodyParams = req.body;
			}

			//拼接核心层最终地址
			var core_server = encodeURI( config.core_server.url + "/" + config.core_server.name + "/" + apiName + "/" + tempRestfulParams );

			console.log(core_server);
			//向核心层发起请求
			R.SEND_HTTP(
					req,
					{
						url    : core_server,	   //请求地址
						method : tempMethod,	   //请求方式
						data   : tempBodyParams	 //body参数
					},
					function (err, data) {

						// 判断是否有错误信息
						if (err) {
							return RES.response(res, false, data);
						}

						return RES.response(res, true, data);
					});

		}

	};

}).call(this);